package com.swotplus.admin.web.weixin;


import com.alibaba.fastjson.JSONObject;
import com.swotplus.system.weixin.entity.WxcmsImgResource;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swotplus.common.core.AjaxResult;
import com.swotplus.framework.web.BaseController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.swotplus.system.weixin.service.WxcmsMediaFilesService;
import java.util.*;
import com.swotplus.system.weixin.entity.WxcmsMediaFiles;
import com.swotplus.system.weixin.service.WxcmsMediaFilesService;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hugang
 * @since 2020-06-04
 */
@Controller
@RequestMapping("/wxcmsMediaFiles")
public class WxcmsMediaFilesController extends BaseController {

    private String prefix = "/wxcmsMediaFiles";


    @Autowired
    private WxcmsMediaFilesService wxcmsMediaFilesService;


    @Autowired
    private WxMpService wxMpService;

    @RequestMapping("/*")
    public String toHtml(){
         return prefix + "/list";
    }

    @RequestMapping("/listData")
    @RequiresPermissions("wxcmsMediaFiles:view")
    @ResponseBody
    public AjaxResult listData(WxcmsMediaFiles wxcmsMediaFiles, Integer page, Integer limit){
        try
        {
            QueryWrapper<WxcmsMediaFiles> wrapper = new QueryWrapper<>();
            Page<WxcmsMediaFiles> pageList = wxcmsMediaFilesService.page(new Page<>(page,limit), wrapper);
            return AjaxResult.success("成功", (int) pageList.getTotal(),pageList.getRecords());
        } catch (Exception e)
        {
            return AjaxResult.warn(e.getMessage());
        }

    }

    /**
     * 新增保存
     */
    @RequestMapping("/add")
    @RequiresPermissions("wxcmsMediaFiles:add")
    @ResponseBody
    public AjaxResult add(WxcmsMediaFiles wxcmsMediaFiles){

        try
        {
            return toAjax(wxcmsMediaFilesService.save(wxcmsMediaFiles));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
    * 删除
    */
    @RequestMapping("/remove")
    @RequiresPermissions("wxcmsMediaFiles:del")
    @ResponseBody
    public  AjaxResult delBatch(String ids){

        try
        {
            List<String> ListStr = Arrays.asList(ids.split(",")).stream().map(s -> s.trim()).collect(Collectors.toList());
            return toAjax(wxcmsMediaFilesService.removeByIds(ListStr));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }
    }

    /**
    * 编辑
    */
    @RequestMapping("/edit")
    @RequiresPermissions("wxcmsMediaFiles:edit")
    @ResponseBody
    public AjaxResult edit(WxcmsMediaFiles wxcmsMediaFiles){
       try
        {
            return toAjax(wxcmsMediaFilesService.updateById(wxcmsMediaFiles));
        } catch (Exception e)
        {
            return error(e.getMessage());
        }
    }




    /**
     *  添加语音\图片\缩略图素材
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("addMateria")
    public AjaxResult addMateria(MultipartFile file,String type) throws Exception {
        JSONObject obj = new JSONObject();
        if (null == file) {
            obj.put("message", "没有文件上传");
        }
        //原文件名称
        String trueName = file.getOriginalFilename();
        //文件后缀名
        String ext = FilenameUtils.getExtension(trueName);

        //系统生成的文件名
        String fileName = file.getOriginalFilename();
        fileName = System.currentTimeMillis() + new Random().nextInt(10000) + "." + ext;
        //文件上传路径
        String resURL = "D:/upload/";
        String filePath = resURL + "/profile/" + fileName;

        File saveFile = new File(filePath);

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        file.transferTo(saveFile);

        WxMpMaterial wxMaterial = new WxMpMaterial();
        wxMaterial.setFile(saveFile);
        wxMaterial.setName(fileName);
        WxMpMaterialUploadResult res = wxMpService.getMaterialService().materialFileUpload(type, wxMaterial);
        String mediaId = res.getMediaId();
        //图片或者图文的缩略图
        if(type.equals("image")||type.equals("thumb")){


//            //图片url
//            String imgUrl = res.getUrl();
//            WxcmsImgResource img = new WxcmsImgResource();
//            img.setName(fileName);
//            img.setSize((int) file.getSize());
//            img.setTrueName(trueName);
//            img.setType(type);//这里用来区分image和thumb
//            img.setUrl(fileName);
//            img.setHttpUrl(imgUrl);
//            img.setMediaId(mediaId);
//
//            String imgRes =imgResourceService.addImg(img);
//
//            //添加base表
//            MsgBase base = new MsgBase();
//            base.setCreateTime(new Date());
//            base.setMsgtype(MediaType.Image.name());
//            baseDao.add(base);
//            //添加到素材表中
//            WxcmsMediaFiles entity = new WxcmsMediaFiles();
//            entity.setMediaId(img.getMediaId());
//            entity.setMediaType(type);
//            entity.setBaseId(base.getId());
//            entity.setCreateTime(LocalDateTime.now());
//            entity.setUpdateTime(LocalDateTime.now());
//            wxcmsMediaFilesService.save(entity);

            obj.put("url", filePath);
            obj.put("imgMediaId", mediaId);
            return AjaxResult.success(obj);
        }else {//音频 voice
            WxcmsMediaFiles mediaFile =new WxcmsMediaFiles();
            mediaFile.setUploadUrl(filePath);
            mediaFile.setTitle(fileName);//用title保存文件名
            mediaFile.setMediaId(mediaId);
            mediaFile.setMediaType(type);
            mediaFile.setCreateTime(LocalDateTime.now());
            mediaFile.setUpdateTime(LocalDateTime.now());
            wxcmsMediaFilesService.save(mediaFile);
            obj.put("url", filePath);
            obj.put("imgMediaId", mediaId);
            return AjaxResult.success(obj);
        }
    }

}

